#pragma once
#include <iostream>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstring>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <pthread.h>
#include <functional>

#include "Log.hpp"
#include "InetAddr.hpp"
#include "Socket.hpp"

const static int defaultsockfd = -1;
const static int gbacklog = 16;

using namespace socket_ns;
using io_service_t = std::function<void(socket_ptr sockfd, InetAddr client)>;

class TcpServer;
class ThreadData
{
public:
    ThreadData(socket_ptr fd, InetAddr addr, TcpServer *s)
        : sockfd(fd), clientaddr(addr), self(s)
    {
    }

public:
    socket_ptr sockfd;
    InetAddr clientaddr;
    TcpServer *self;
};

class TcpServer
{
public:
    TcpServer(uint16_t port, io_service_t service)
        : _localaddr("0.0.0.0", port),
          _listensock(std::make_unique<TcpSocket>()),
          _service(service),
          _isrunning(false)
    {
        _listensock->BuildListenSocket(_localaddr);
    }

    static void *HandlerSock(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        td->self->_service(td->sockfd, td->clientaddr);
        ::close(td->sockfd->SockFd());
        delete td;
        return nullptr;
    }

    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            InetAddr peeraddr;

            socket_ptr normalsock = _listensock->Accepter(&peeraddr);
            if (normalsock == nullptr)
            {
                LOG(WARNING, "accept error \n");
                continue;
            }

            pthread_t t;
            ThreadData *td = new ThreadData(normalsock, peeraddr, this);
            pthread_create(&t, nullptr, HandlerSock, td);
        }
         _isrunning = false;
    }

private:
    InetAddr _localaddr;
    std::unique_ptr<Socket> _listensock;
    bool _isrunning;

    io_service_t _service;
};